using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace DocumentCreationSystem.Services;

/// <summary>
/// AI工具服务实现
/// </summary>
public class AIToolsService : IAIToolsService
{
    private readonly ILogger<AIToolsService> _logger;
    private readonly IProjectToolsService _projectToolsService;
    private readonly Dictionary<string, AITool> _aiTools;
    private readonly List<AIToolUsageHistory> _usageHistory;

    public AIToolsService(
        ILogger<AIToolsService> logger,
        IProjectToolsService projectToolsService)
    {
        _logger = logger;
        _projectToolsService = projectToolsService;
        _aiTools = new Dictionary<string, AITool>();
        _usageHistory = new List<AIToolUsageHistory>();

        InitializeAITools();
    }

    private void InitializeAITools()
    {
        // 代码库搜索工具
        RegisterAITool(new AITool
        {
            Id = "search-codebase",
            Name = "代码库搜索",
            Description = "基于自然语言描述的智能代码检索工具",
            Category = "代码搜索",
            Icon = "Search",
            Tags = new List<string> { "搜索", "代码", "智能" }
        });

        RegisterAITool(new AITool
        {
            Id = "search-by-regex",
            Name = "正则表达式搜索",
            Description = "正则表达式快速匹配工具",
            Category = "代码搜索",
            Icon = "Regex",
            Tags = new List<string> { "搜索", "正则", "匹配" }
        });

        // 文件操作工具
        RegisterAITool(new AITool
        {
            Id = "view-files",
            Name = "批量查看文件",
            Description = "批量查看文件内容（支持多文件同时查看）",
            Category = "文件操作",
            Icon = "FileView",
            Tags = new List<string> { "文件", "查看", "批量" }
        });

        RegisterAITool(new AITool
        {
            Id = "list-dir",
            Name = "目录结构浏览",
            Description = "目录结构浏览工具",
            Category = "文件操作",
            Icon = "Folder",
            Tags = new List<string> { "目录", "浏览", "结构" }
        });

        RegisterAITool(new AITool
        {
            Id = "write-to-file",
            Name = "文件创建/覆写",
            Description = "文件创建/覆写工具",
            Category = "文件操作",
            Icon = "FileWrite",
            Tags = new List<string> { "文件", "创建", "写入" }
        });

        RegisterAITool(new AITool
        {
            Id = "update-file",
            Name = "代码块替换式文件编辑",
            Description = "代码块替换式文件编辑工具",
            Category = "文件操作",
            Icon = "FileEdit",
            Tags = new List<string> { "文件", "编辑", "替换" }
        });

        // 开发辅助工具
        RegisterAITool(new AITool
        {
            Id = "run-command",
            Name = "命令行执行",
            Description = "命令行执行工具（支持PowerShell）",
            Category = "开发辅助",
            Icon = "Terminal",
            Tags = new List<string> { "命令行", "执行", "PowerShell" }
        });

        RegisterAITool(new AITool
        {
            Id = "open-preview",
            Name = "本地服务预览",
            Description = "本地服务预览工具",
            Category = "开发辅助",
            Icon = "Preview",
            Tags = new List<string> { "预览", "服务", "本地" }
        });

        // 网络工具
        RegisterAITool(new AITool
        {
            Id = "web-search",
            Name = "联网搜索",
            Description = "联网搜索工具",
            Category = "网络工具",
            Icon = "Globe",
            Tags = new List<string> { "搜索", "网络", "联网" }
        });

        // MCP集成工具
        RegisterAITool(new AITool
        {
            Id = "excel-automation",
            Name = "Excel自动化",
            Description = "Excel自动化工具集",
            Category = "MCP集成",
            Icon = "Excel",
            Tags = new List<string> { "Excel", "自动化", "办公" }
        });

        RegisterAITool(new AITool
        {
            Id = "blender-automation",
            Name = "Blender三维建模",
            Description = "Blender三维建模工具集",
            Category = "MCP集成",
            Icon = "Blender",
            Tags = new List<string> { "Blender", "3D", "建模" }
        });

        RegisterAITool(new AITool
        {
            Id = "browser-automation",
            Name = "浏览器自动化",
            Description = "浏览器自动化工具集",
            Category = "MCP集成",
            Icon = "Browser",
            Tags = new List<string> { "浏览器", "自动化", "网页" }
        });

        // AI辅助工具
        RegisterAITool(new AITool
        {
            Id = "ai-content-generator",
            Name = "AI内容生成器",
            Description = "使用AI生成各类内容",
            Category = "AI辅助",
            Icon = "Robot",
            Tags = new List<string> { "AI", "生成", "内容" }
        });

        RegisterAITool(new AITool
        {
            Id = "content-analyzer",
            Name = "内容分析器",
            Description = "分析文档内容质量和特征",
            Category = "内容分析",
            Icon = "Analytics",
            Tags = new List<string> { "分析", "内容", "质量" }
        });

        _logger.LogInformation($"已初始化 {_aiTools.Count} 个AI工具");
    }

    private void RegisterAITool(AITool tool)
    {
        _aiTools[tool.Id] = tool;
    }

    public async Task<List<AITool>> GetAvailableToolsAsync()
    {
        try
        {
            return _aiTools.Values.Where(t => t.IsEnabled).ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取可用AI工具失败");
            return new List<AITool>();
        }
    }

    public async Task<List<AITool>> GetToolsByCategoryAsync(string category)
    {
        try
        {
            return _aiTools.Values
                .Where(t => t.IsEnabled && t.Category.Equals(category, StringComparison.OrdinalIgnoreCase))
                .ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取类别 {category} 的AI工具失败");
            return new List<AITool>();
        }
    }

    public async Task<AIToolExecutionResult> ExecuteToolAsync(string toolId, Dictionary<string, object> parameters)
    {
        var stopwatch = Stopwatch.StartNew();
        var result = new AIToolExecutionResult { ToolId = toolId };

        try
        {
            if (!_aiTools.TryGetValue(toolId, out var tool))
            {
                throw new ArgumentException($"未找到AI工具: {toolId}");
            }

            if (!tool.IsEnabled)
            {
                throw new InvalidOperationException($"AI工具已禁用: {toolId}");
            }

            // 执行工具
            var projectToolResult = await _projectToolsService.ExecuteToolAsync(toolId, parameters);

            // 转换结果
            result.IsSuccess = projectToolResult.IsSuccess;
            result.Message = projectToolResult.Message;
            result.Data = projectToolResult.Data;
            result.ErrorDetails = projectToolResult.ErrorDetails;
            result.ExecutionTimeMs = stopwatch.ElapsedMilliseconds;
            result.Logs = projectToolResult.Logs;

            // 更新工具统计
            tool.UsageCount++;
            tool.LastUsedAt = DateTime.Now;
            
            // 更新平均执行时间
            tool.AverageExecutionTimeMs = (tool.AverageExecutionTimeMs * (tool.UsageCount - 1) + result.ExecutionTimeMs) / tool.UsageCount;
            
            // 更新成功率
            var successCount = _usageHistory.Count(h => h.ToolId == toolId && h.IsSuccess);
            if (result.IsSuccess) successCount++;
            tool.SuccessRate = tool.UsageCount > 0 ? (double)successCount / tool.UsageCount * 100 : 100;

            // 记录使用历史
            _usageHistory.Add(new AIToolUsageHistory
            {
                ToolId = toolId,
                UsedAt = DateTime.Now,
                Parameters = parameters,
                IsSuccess = result.IsSuccess,
                ExecutionTimeMs = result.ExecutionTimeMs,
                ErrorMessage = result.ErrorDetails
            });

            // 限制历史记录数量
            if (_usageHistory.Count > 1000)
            {
                _usageHistory.RemoveRange(0, _usageHistory.Count - 1000);
            }

            _logger.LogInformation($"AI工具 {toolId} 执行完成，耗时 {result.ExecutionTimeMs}ms");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"执行AI工具 {toolId} 时发生错误");
            result.IsSuccess = false;
            result.Message = "执行失败";
            result.ErrorDetails = ex.Message;
            result.ExecutionTimeMs = stopwatch.ElapsedMilliseconds;
        }

        return result;
    }

    public async Task<List<AIToolParameter>> GetToolParametersAsync(string toolId)
    {
        try
        {
            // 从ProjectToolsService获取工具参数
            var projectTools = await _projectToolsService.GetAvailableToolsAsync("All");
            var projectTool = projectTools.FirstOrDefault(t => t.Id == toolId);

            if (projectTool == null)
            {
                return new List<AIToolParameter>();
            }

            // 转换参数格式
            return projectTool.Parameters.Select(p => new AIToolParameter
            {
                Name = p.Name,
                DisplayName = p.DisplayName,
                Type = p.Type,
                IsRequired = p.IsRequired,
                DefaultValue = p.DefaultValue,
                Description = p.Description ?? "",
                Options = p.Options ?? new List<string>()
            }).ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取工具 {toolId} 参数失败");
            return new List<AIToolParameter>();
        }
    }

    public async Task<AIToolValidationResult> ValidateParametersAsync(string toolId, Dictionary<string, object> parameters)
    {
        var result = new AIToolValidationResult();

        try
        {
            var toolParameters = await GetToolParametersAsync(toolId);

            // 检查必需参数
            foreach (var param in toolParameters.Where(p => p.IsRequired))
            {
                if (!parameters.ContainsKey(param.Name) || parameters[param.Name] == null)
                {
                    result.Errors.Add($"缺少必需参数: {param.DisplayName}");
                }
            }

            // 检查参数类型和值
            foreach (var kvp in parameters)
            {
                var param = toolParameters.FirstOrDefault(p => p.Name == kvp.Key);
                if (param != null)
                {
                    var validationError = ValidateParameterValue(param, kvp.Value);
                    if (!string.IsNullOrEmpty(validationError))
                    {
                        result.Errors.Add(validationError);
                    }
                }
            }

            result.IsValid = result.Errors.Count == 0;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"验证工具 {toolId} 参数失败");
            result.IsValid = false;
            result.Errors.Add($"参数验证失败: {ex.Message}");
        }

        return result;
    }

    private string ValidateParameterValue(AIToolParameter param, object value)
    {
        try
        {
            switch (param.Type.ToLower())
            {
                case "integer":
                case "int":
                    if (!int.TryParse(value?.ToString(), out var intValue))
                    {
                        return $"参数 {param.DisplayName} 必须是整数";
                    }
                    if (param.MinValue.HasValue && intValue < param.MinValue.Value)
                    {
                        return $"参数 {param.DisplayName} 不能小于 {param.MinValue.Value}";
                    }
                    if (param.MaxValue.HasValue && intValue > param.MaxValue.Value)
                    {
                        return $"参数 {param.DisplayName} 不能大于 {param.MaxValue.Value}";
                    }
                    break;

                case "boolean":
                case "bool":
                    if (!bool.TryParse(value?.ToString(), out _))
                    {
                        return $"参数 {param.DisplayName} 必须是布尔值";
                    }
                    break;

                case "string":
                    var stringValue = value?.ToString() ?? "";
                    if (param.Options.Any() && !param.Options.Contains(stringValue))
                    {
                        return $"参数 {param.DisplayName} 必须是以下值之一: {string.Join(", ", param.Options)}";
                    }
                    break;
            }

            return string.Empty;
        }
        catch
        {
            return $"参数 {param.DisplayName} 验证失败";
        }
    }

    public async Task<List<AIToolUsageHistory>> GetToolUsageHistoryAsync(string toolId, int limit = 10)
    {
        try
        {
            return _usageHistory
                .Where(h => h.ToolId == toolId)
                .OrderByDescending(h => h.UsedAt)
                .Take(limit)
                .ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"获取工具 {toolId} 使用历史失败");
            return new List<AIToolUsageHistory>();
        }
    }

    public async Task<List<AITool>> SearchToolsAsync(string query)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(query))
            {
                return await GetAvailableToolsAsync();
            }

            var lowerQuery = query.ToLower();
            return _aiTools.Values
                .Where(t => t.IsEnabled && (
                    t.Name.ToLower().Contains(lowerQuery) ||
                    t.Description.ToLower().Contains(lowerQuery) ||
                    t.Category.ToLower().Contains(lowerQuery) ||
                    t.Tags.Any(tag => tag.ToLower().Contains(lowerQuery))
                ))
                .OrderByDescending(t => CalculateRelevanceScore(t, lowerQuery))
                .ToList();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"搜索AI工具失败: {query}");
            return new List<AITool>();
        }
    }

    private double CalculateRelevanceScore(AITool tool, string query)
    {
        double score = 0;

        if (tool.Name.ToLower().Contains(query)) score += 10;
        if (tool.Description.ToLower().Contains(query)) score += 5;
        if (tool.Category.ToLower().Contains(query)) score += 3;

        foreach (var tag in tool.Tags)
        {
            if (tag.ToLower().Contains(query)) score += 2;
        }

        // 考虑使用频率
        score += Math.Log(tool.UsageCount + 1);

        return score;
    }

    public async Task<AIToolStatistics> GetToolStatisticsAsync()
    {
        try
        {
            var statistics = new AIToolStatistics
            {
                TotalTools = _aiTools.Count,
                EnabledTools = _aiTools.Values.Count(t => t.IsEnabled),
                TotalUsageCount = _aiTools.Values.Sum(t => t.UsageCount),
                AverageSuccessRate = _aiTools.Values.Any() ? _aiTools.Values.Average(t => t.SuccessRate) : 100.0,
                MostUsedTools = _aiTools.Values
                    .OrderByDescending(t => t.UsageCount)
                    .Take(5)
                    .Select(t => t.Name)
                    .ToList(),
                CategoryCounts = _aiTools.Values
                    .GroupBy(t => t.Category)
                    .ToDictionary(g => g.Key, g => g.Count())
            };

            return statistics;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取AI工具统计信息失败");
            return new AIToolStatistics();
        }
    }
}
